/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.sales.hancadsa.client.presenter;

import br.com.sales.generics.client.HanAbstractPresenter;
import br.com.sales.generics.client.components.autocomplete.widget.Autocomplete;
import br.com.sales.generics.client.components.mask.MaskEditHandler;
import br.com.sales.generics.client.nametoken.NameTokens;
import br.com.sales.generics.client.request.HannaCallBack;
import br.com.sales.generics.client.utils.User;
import br.com.sales.hancadsa.client.presenter.behavior.HanCadSABehavior;
import static br.com.sales.hancadsa.client.presenter.consts.HanCadSAConts.CELL_EDITING;
import static br.com.sales.hancadsa.client.presenter.consts.HanCadSAConts.CELL_REMOVING;
import br.com.sales.hancadsa.client.presenter.utils.HanCadSAUtils;
import br.com.sales.hancadsa.client.view.HanCadSAResources;
import br.com.sales.hancadsa.client.view.widget.FinishSaleDialog;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.web.bindery.event.shared.EventBus;
import com.gwtplatform.mvp.client.HasUiHandlers;
import com.gwtplatform.mvp.client.View;
import com.gwtplatform.mvp.client.annotations.NameToken;
import com.gwtplatform.mvp.client.annotations.ProxyStandard;
import com.gwtplatform.mvp.client.proxy.ProxyPlace;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author v
 */
public class HanCadSAPresenter
        extends HanAbstractPresenter<HanCadSAPresenter.Display, HanCadSAPresenter.MyProxy>
        implements HanCadSAUiHandler {

    private static final int COUNT_COLUMN = 2;
    private static final int PRICE_COLUMN = 1;
    @Inject
    private Provider<User> user;
    private boolean isEditing = false;
    private boolean isNewRecord = false;
    private int rowEditing;
    @Inject
    private FinishSaleDialog finishSaleDialog;
    @Inject
    private HanCadSABehavior behavior;

    @Inject
    public HanCadSAPresenter(EventBus eventBus,
            HanCadSAPresenter.Display view,
            HanCadSAPresenter.MyProxy proxy) {
        super(eventBus, view, proxy);
        getView().setUiHandlers(this);
    }

    @Override
    protected void onBind() {
        getView().build();
        behavior.onChangeProduct(getView());
        behavior.onChangeCount(getView());
    }

    @Override
    protected void onReveal() {
        super.onReveal();
        adjustStatusField();
    }

    @Override
    public void onClickAddItem(ClickEvent event) {
        if (!getView().getProductEdit().getText().isEmpty()
                && !"".equals(getView().getPriceEdit().getValue())
                && getView().getPriceEdit().getValue() != null
                && !"".equals(getView().getCountEdit().getValue())
                && getView().getCountEdit().getValue() != null) {
            getView().setMandatory();
            int verifer = verifer();
            if (verifer == 0) {
                int rowIndex = getView().getItemsGrid().getRowCount();
                addRow(getView().getProductEdit().getText(), rowIndex, 0);
                addRow(getView().getPriceEdit().getValueFormated(), rowIndex, 1);
                addRow(getView().getCountEdit().getValue(), rowIndex, 2);
                addRow(new Image(HanCadSAResources.INSTANCE.edit()), rowIndex, CELL_EDITING);
                addRow(new Image(HanCadSAResources.INSTANCE.cancel()), rowIndex, CELL_REMOVING);
            } else {
                int value = Integer.parseInt(getView().getItemsGrid().getText(verifer, 2))
                        + Integer.parseInt(getView().getCountEdit().getValue());
                addRow(value, verifer, 2);
            }
            isEditing = false;
            rowEditing = 0;
            behavior.setIsEditing(isEditing);
            calculateSale();
            cleaning();
            getView().getCancelItem().setVisible(false);
        } else {
            getView().setMandatory();
        }
    }

    private int verifer() {
        int returnInt = 0;
        if (!isEditing) {
            for (int row = 1; row < getView().getItemsGrid().getRowCount(); row++) {
                int value = Integer.parseInt(getView().getProductEdit().getValueMap().get(getView().getItemsGrid().getText(row, 0)));
                if (Integer.parseInt(getView().getProductEdit().getValue()) == value) {
                    returnInt = row;
                }
            }
        }
        return returnInt;
    }

    @Override
    public void editRecorg(int row) {
        getView().getCancelItem().setVisible(true);
        rowEditing = row;
        isEditing = true;
        behavior.setIsEditing(isEditing);
        getView().getProductEdit().setValue(getView().getItemsGrid().getText(row, 0), getView().getProductEdit().getValueMap().get(getView().getItemsGrid().getText(row, 0)));
        getView().getPriceEdit().setValue(getView().getItemsGrid().getText(row, 1));
        getView().getCountEdit().setValue(getView().getItemsGrid().getText(row, 2));
    }

    @Override
    public void addRow(Object value, int row, int cell) {
        if (isEditing) {
            Widget widget = getView().createCellWidget(value);
            getView().getItemsGrid().setWidget(rowEditing, cell, widget);
            getView().getItemsGrid().getCellFormatter().addStyleName(rowEditing, cell, "flextable-cell");

        } else {
            Widget widget = getView().createCellWidget(value);
            getView().getItemsGrid().setWidget(row, cell, widget);
            getView().getItemsGrid().getCellFormatter().addStyleName(row, cell, "flextable-cell");
            getView().getProductEdit().setFocus(true);
        }
    }

    @Override
    public void onClickCancelItem(ClickEvent event) {
        cleaning();
        rowEditing = 0;
        isEditing = false;
        getView().getCancelItem().setVisible(false);
    }

    @Override
    public void calculateSale() {
        Double attirbuteValue = 0D;
        int countProduct = 0;
        for (int index = 1; index < getView().getItemsGrid().getRowCount(); index++) {
            countProduct += Integer.parseInt(getView().getItemsGrid().getText(index, COUNT_COLUMN));
            attirbuteValue
                    += (Double.parseDouble(getView().getItemsGrid().getText(index, PRICE_COLUMN).replaceAll(",", "")) * countProduct);
            countProduct = 0;
        }
        NumberFormat format = NumberFormat.getDecimalFormat();
        getView().getValueTotalSalesLbl().setText("(R$) " + format.overrideFractionDigits(2).format(attirbuteValue));
        getView().getValueTotalSalesLbl().setVisible(attirbuteValue > 0.0);
        getView().getTotalSalesLbl().setVisible(attirbuteValue > 0.0);
    }

    public void setDefaultValues() {
        DateTimeFormat format = DateTimeFormat.getFormat("dd/MM/yyyy HH:mm:ss");
        getView().getDateEdit().setText(format.format(new Date(System.currentTimeMillis())));
        getView().getUsuarioEdit().setText(user.get().getNmUser());
        adjustStatusField();
    }

    @Override
    public void cleaning() {
        getView().getProductEdit().setValue(null);
        getView().getPriceEdit().setValue(null);
        HanCadSAUtils.clear(getView().getCountEdit());
    }

    @Override
    public void onClickfinishedSales(ClickEvent event) {
        if (isNewRecord) {
            if (getView().getCompleteClient().getValue() == null || "".equals(getView().getCompleteClient().getValue())) {
                getView().getCompleteClient().getElement().addClassName("mandatory");
                return;
            } else {
                getView().getCompleteClient().getElement().removeClassName("mandatory");
            }
            if (getView().getItemsGrid().getRowCount() == 1) {
                Window.alert("Sem produtos cadastrados! \n Não pode ser finalizado sem produtos!");
                return;
            }
            List<Map> productList = new ArrayList<>();
            for (int index = 0; index < getView().getItemsGrid().getRowCount(); index++) {
                if (index > 0) {
                    Map itemSales = new LinkedHashMap();
                    itemSales.put("ID_PRODUCT", getView().getProductEdit().getValueMap().get(getView().getItemsGrid().getText(index, 0)));
                    itemSales.put("VL_PRICE", getView().getItemsGrid().getText(index, 1));
                    itemSales.put("COUNT", getView().getItemsGrid().getText(index, 2));
                    productList.add(itemSales);
                }
            }

            Map sale = new LinkedHashMap();
            sale.put("DT_REGISTER", getView().getDateEdit().getText());
            sale.put("NM_USER", getView().getUsuarioEdit().getText());
            sale.put("CLIENT", getView().getCompleteClient().getValue());
            sale.put("TOTAL", getView().getValueTotalSalesLbl().getText());
            sale.put("ITEM_SALES", productList);
            finishSaleDialog.setModal(isEditing);
            finishSaleDialog.show(sale, new HannaCallBack() {

                @Override
                public void onReady(Object value) {
                    isNewRecord = false;
                    behavior.adjusterCached(getView());
                    clear();
                }
            });
        }
    }

    @Override
    public void clear() {
        int rows = getView().getItemsGrid().getRowCount();
        for (int i = rows - 1; i > 0; i--) {
            getView().getItemsGrid().removeRow(i);
        }
        getView().getDateEdit().setText(null);
        getView().getUsuarioEdit().setText(null);
        getView().getCompleteClient().setValue(null);
        getView().getTotalSalesLbl().setVisible(false);
        getView().getValueTotalSalesLbl().setVisible(false);
        getView().getCountEdit().setValue(null);
        getView().getPriceEdit().setValue(null);
        getView().getProductEdit().setValue(null);
        isEditing = false;
        isNewRecord = false;
        adjustStatusField();
    }

    private void adjustStatusField() {
        getView().getDateEdit().setReadOnly(!isNewRecord);
        getView().getUsuarioEdit().setReadOnly(!isNewRecord);
        getView().getCompleteClient().setReadOnly(!isNewRecord);
        getView().getCountEdit().setReadOnly(!isNewRecord);
        getView().getPriceEdit().setReadOnly(!isNewRecord);
        getView().getProductEdit().setReadOnly(!isNewRecord);
    }

    @Override
    public void onClickCancel(ClickEvent event) {
        if (isNewRecord) {
            if (Window.confirm("Deseja cancelar?")) {
                adjustStatusField();
                clear();
            }
        }
    }

    @Override
    public void onClickNew(ClickEvent event) {
        if (!isNewRecord) {
            setDefaultValues();
            isNewRecord = true;
            adjustStatusField();
        } else {
            if (Window.confirm("Deseja cancelar a edição atual?")) {
                clear();
                setDefaultValues();
                isNewRecord = true;
                adjustStatusField();
            }
        }
        getView().getCompleteClient().setFocus(isNewRecord);
    }

    @ProxyStandard
    @NameToken(NameTokens.NEW_SALES)
    public interface MyProxy extends ProxyPlace<HanCadSAPresenter> {
    }

    public static interface Display extends View, HasUiHandlers<HanCadSAUiHandler> {

        Label getValueTotalSalesLbl();

        Label getTotalSalesLbl();

        TextBox getDateEdit();

        TextBox getUsuarioEdit();

        void build();

        MaskEditHandler getPriceEdit();

        Autocomplete getProductEdit();

        TextBox getCountEdit();

        FlexTable getItemsGrid();

        void adjustStatusFields();

        void setMandatory();

        Widget createCellWidget(Object cellObject);

        Autocomplete getCompleteClient();

        Button getAddItem();

        Button getCancelItem();
    }
}
